package com.piece.flowable.controller;

import com.piece.core.framework.annotation.permission.AclPermission;
import com.piece.core.framework.annotation.permission.SubmitPermission;
import com.piece.core.framework.constant.ExceptionConstants;
import com.piece.core.framework.enums.StatusType;
import com.piece.core.framework.support.bootstrap.DataTable;
import com.piece.core.framework.support.bootstrap.QueryTable;
import com.piece.core.framework.support.bootstrap.Valid;
import com.piece.core.framework.support.convert.Convert;
import com.piece.core.framework.support.response.AjaxResponse;
import com.piece.core.framework.util.basic.I18nUtil;
import com.piece.core.framework.util.string.StringUtil;
import com.piece.core.log.config.UserContextHolder;
import com.piece.core.web.controller.FrameWorkController;
import com.piece.module.flowable.model.WfDeployForm;
import com.piece.module.flowable.model.WfForm;
import com.piece.module.flowable.service.WfDeployFormService;
import com.piece.module.flowable.service.WfFormService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

@Slf4j
@RestController
@Api(tags = {"流程表单管理"})
@RequestMapping("/api/workflow/form")
public class WfFormController extends FrameWorkController {

    @Resource
    private WfFormService wfFormService;

    @Resource
    private WfDeployFormService wfDeployFormService;

    @PostMapping("/list")
    @AclPermission(code = "flowable:form:view")
    @ApiOperation(value = "查询流程表单列表")
    @ApiImplicitParam(value = "查询条件", dataTypeClass = QueryTable.class, type = "body")
    public List list() {
        QueryTable queryTable = initTable();
        DataTable dataTable = wfFormService.findPage(queryTable);
        return dataTable.getData();
    }

    @PostMapping("/table")
    @AclPermission(code = "flowable:form:view")
    @ApiOperation(value = "查询流程表单分页数据")
    @ApiImplicitParam(value = "查询条件", dataTypeClass = QueryTable.class, type = "body")
    public AjaxResponse table() {
        QueryTable queryTable = initTable();
        DataTable dataTable = wfFormService.findPage(queryTable);
        return success(dataTable);
    }

    @GetMapping("/load")
    @AclPermission(code = "flowable:form:view")
    @ApiOperation(value = "加载流程表单数据")
    @ApiImplicitParam(name="id", value = "主键")
    public AjaxResponse load() {
        Long id = Convert.toLong(getRequest().getParameter("id"), null);
        WfForm wfForm = new WfForm();
        if (null != id) {
            wfForm = wfFormService.findById(id);
        }
        return success(wfForm);
    }

    @SubmitPermission
    @PostMapping("/save")
    @AclPermission(code = "flowable:form:add,flowable:form:edit")
    @ApiOperation(value = "保存流程表单数据")
    @ApiImplicitParam(value = "流程表单数据", dataTypeClass = WfForm.class, type = "body")
    public AjaxResponse save() {
        WfForm wfForm;
        try {
            Long id = Convert.toLong(getRequest().getParameter("formId"), null);
            if (null != id) {
                wfForm = wfFormService.findById(id);
            } else {
                wfForm = new WfForm();
            }
            initDB(wfForm);
            generateDefaultValue(wfForm);
            wfFormService.insertOrUpdate(wfForm);
            return success(I18nUtil.message(ExceptionConstants.SAVE_SUCCESS), null);
        } catch (Exception e) {
            return error(I18nUtil.message(ExceptionConstants.SAVE_FAILURE), e.getMessage());
        }
    }

    @SubmitPermission
    @PostMapping("/saveDeployForm")
    @AclPermission(code = "flowable:form:edit")
    @ApiOperation(value = "保存流程表单数据")
    @ApiImplicitParam(value = "流程表单数据", dataTypeClass = WfDeployForm.class, type = "body")
    public AjaxResponse saveDeployForm() {
        try {
            WfDeployForm deployForm = new WfDeployForm();
            initDB(deployForm);
            wfDeployFormService.insert(deployForm);
            return success(I18nUtil.message(ExceptionConstants.SAVE_SUCCESS), null);
        } catch (Exception e) {
            return error(I18nUtil.message(ExceptionConstants.SAVE_FAILURE), e.getMessage());
        }
    }

    @SubmitPermission
    @PostMapping("/delete")
    @AclPermission(code = "flowable:form:delete")
    @ApiOperation(value = "删除流程表单")
    @ApiImplicitParam(name = "ids", value="主键集合")
    public AjaxResponse delete() throws Exception {
        String ids = getRequest().getParameter("ids");
        if (StringUtil.isNotEmpty(ids)) {
            wfFormService.delete(Convert.toLongArray(ids));
        }
        return success(I18nUtil.message(ExceptionConstants.DELETE_SUCCESS), null);
    }

    @GetMapping("/unique")
    @ApiOperation(value = "检查流程表单名称是否重复")
    public Valid checkUserIsUnique() {
        String id = getRequest().getParameter("id");
        String formName = getRequest().getParameter("formName");
        boolean result = wfFormService.checkFormNameUnique(Convert.toLong(id), formName);
        Valid valid = new Valid();
        valid.setValid(result);
        return valid;
    }

    private void generateDefaultValue(WfForm wfForm) {
        if (null != wfForm.getFormId()) {
            wfForm.setCreateBy(UserContextHolder.getUserId());
            wfForm.setCreateTime(new Date());
        }

        wfForm.setUpdateBy(UserContextHolder.getUserId());
        wfForm.setUpdateTime(new Date());
        wfForm.setStatus(StatusType.NORMAL.getCode());
    }
}
